package com.core.shared;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 16-1-5
 * Time: 上午10:35
 * To change this template use File | Settings | File Templates.
 */
public class IDCardHandle {

    public static final String IDCardReg = "[\\d]{15}|[\\d]{17}x|[\\d]{18}";

    /**
     * 验证身份证最后一位是否合法，仅18位可验证
     *
     * @param idCard
     * @return
     */
    public static boolean idCardValidate(String idCard) {
        if (idCard.length() == 18) {
            String num = lastNum(idCard);
            if (num.equals(idCard.substring(17))) {
                return true;
            }
        }
        return false;
    }

    private static String lastNum(String idCard) {
        String result = "";
        String str = idCard.substring(0, 17);
        char[] array = str.toCharArray();
        int[] data = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum += Integer.parseInt(array[i] + "") * data[i];
        }
        int a = sum % 11;
        switch (a) {
            case 0:
                result = "1";
                break;
            case 1:
                result = "0";
                break;
            case 2:
                result = "x";
                break;
            case 3:
                result = "9";
                break;
            case 4:
                result = "8";
                break;
            case 5:
                result = "7";
                break;
            case 6:
                result = "6";
                break;
            case 7:
                result = "5";
                break;
            case 8:
                result = "4";
                break;
            case 9:
                result = "3";
                break;
            case 10:
                result = "2";
                break;
            default:

        }
        return result;
    }

}
